﻿''' <summary>
''' This helper is used for DevExpress Xtragrid.
''' </summary>
''' <remarks></remarks>
Public NotInheritable Class DevExGridHelper
    ''' <summary>
    ''' Based on the Microsoft format expression
    ''' </summary>
    ''' <param name="arow"></param>
    ''' <returns>DevExpress.Utils.FormatType</returns>
    ''' <remarks> refer to for more information
    ''' http://documentation.devexpress.com/#WindowsForms/CustomDocument2141 </remarks>
    Public Shared Function GetFormatType(ByVal arow As DataRow) As DevExpress.Utils.FormatType
        If (Not String.IsNullOrEmpty(arow("pNumberFormatID_FK").ToString)) Then
            Select Case CType(arow("pNumberFormatID_FK"), Guid)

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_CURRENCY, CommonExt.Base.IdRepository.META_NUMBERFORMAT_GENERALNUMBER, CommonExt.Base.IdRepository.META_NUMBERFORMAT_PERCENT, CommonExt.Base.IdRepository.META_NUMBERFORMAT_STANDARD, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SCIENTIFIC
                    Return DevExpress.Utils.FormatType.Numeric

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_GENERALDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_LONGDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_LONGTIME, CommonExt.Base.IdRepository.META_NUMBERFORMAT_MEDIUMDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_MEDIUMTIME, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SHORTDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SHORTTIME
                    Return DevExpress.Utils.FormatType.DateTime

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_FORMATEXPR
                    Return DevExpress.Utils.FormatType.Custom

                Case Else
                    Return DevExpress.Utils.FormatType.None
            End Select
        Else
            Return DevExpress.Utils.FormatType.None
        End If
    End Function

    Public Shared Sub AssignCustomSummaryProperties(ByVal view As GridView, ByVal column As GridColumn, ByVal arow As DataRow)
        If Not IsDBNull(arow("pSummaryInfo")) Then
            view.OptionsView.ShowFooter = True
            column.SummaryItem.DisplayFormat = arow("pSummaryInfo").ToString

            If column.SummaryItem.DisplayFormat.StartsWith("SUM") Then
                column.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum
            ElseIf column.SummaryItem.DisplayFormat.StartsWith("AVG") Then
                column.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Average
            ElseIf column.SummaryItem.DisplayFormat.StartsWith("COUNT") Then
                column.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count
            ElseIf column.SummaryItem.DisplayFormat.StartsWith("MIN") Then
                column.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Min
            ElseIf column.SummaryItem.DisplayFormat.StartsWith("MAX") Then
                column.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Max
            Else
                column.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.None
            End If
        End If
    End Sub
    ''' <summary>
    ''' Just a helper for summary type on Pivot field
    ''' </summary>
    ''' <param name="field"></param>
    ''' <param name="arow"></param>
    ''' <remarks>need more validation if string is not a number within Pivot summaryType</remarks>
    Public Shared Sub AssignPivotSummaryItemType(ByVal field As PivotGridField, ByVal arow As DataRow)
        If Not String.IsNullOrEmpty(arow("pSummaryInfo").ToString) Then
            field.SummaryType = CType(arow("pSummaryInfo"), PivotSummaryType)
        End If
    End Sub


    ''' <summary>
    ''' Format all the grid column base on Metacolumns configuration.
    ''' </summary>
    ''' <param name="view">View to format</param>
    ''' <param name="metaData">DataTable that contains the columns configuration</param>
    ''' <remarks>OutStandingIssue</remarks>
    Public Shared Sub BuildColumns(ByVal view As GridView, ByVal metaData As DataTable)
        Throw New NotImplementedException("----- BuildColumns --------")
    End Sub
    ''' <summary>
    ''' LOV Assignation
    ''' </summary>
    ''' <param name="aView"></param>
    ''' <param name="aMetaDataTable"></param>
    ''' <param name="gridControl"></param>
    ''' <remarks></remarks>
    Public Shared Sub AssignLKP(ByVal aView As GridView, ByVal aMetaDataTable As MetaDataTable, ByVal gridControl As GridControl)
        Dim aMetaquery As MetaQuery
        Dim colVisible As Boolean
        Dim View As Views.Base.ColumnView '= aLOV.View
        Dim Column As DevExpress.XtraGrid.Columns.GridColumn
        Dim aLOV As RepositoryItemGridLookUpEdit
        Dim formatType As DevExpress.Utils.FormatType

        Dim indexForLang As Integer

        Dim hideCol As Boolean
        Dim colname As String

        Dim objCache As Object

        'TODO POUR TR: Tenir compte du TR si on la de défini dans la metaquery sinon utiliser le LOV
        Try

            For Each lookup As KeyValuePair(Of String, Guid) In aMetaDataTable.ListOfVisibleLookup
                aLOV = Nothing
                'Cherche si on a déjà ce LOV dans la grille
                For Each lov As RepositoryItem In gridControl.RepositoryItems
                    If lov.Name = lookup.Value.ToString Then
                        aLOV = TryCast(lov, RepositoryItemGridLookUpEdit)
                    End If
                Next

                'Si on l'a pas on le créer
                If aLOV Is Nothing Then
                    'testPoint: Verify the GuidField in metaquery , The Guidfield is CASE sensitive, IE: ListvalueID is not equal to ListValueId
                    'testPoint: LOV Query Must have the first 4 field Like GUID, Code, Desc_PRM, Desc_ALT in the SELECT Statement


                    'TestPoint: On cache le résultat du LOV. (aMetaquery.ResultQuery)
                    '           Les MetaColumns
                    '           La metaquery
                    objCache = Cache.CacheExt.GetCacheObject(lookup.Value.ToString)
                    If objCache Is Nothing Then
                        aMetaquery = CommonExt.MetaQuery.GetMetaQueryById(lookup.Value)
                        aMetaquery.FillResultQuery()
                        Select Case aMetaquery.QueryID
                            'TestPoint: Core LOV are store in cache as long as possible
                            Case IdRepository.LOV_Lot, IdRepository.LOV_LotStatus, IdRepository.LOV_Product, IdRepository.LOV_SiteSection, IdRepository.LOV_SpecTest, IdRepository.LOV_SpecificationAll, IdRepository.LOV_TranType, IdRepository.LOV_Units, IdRepository.MetaLOVCaptions, IdRepository.MetaLOVToolTip, IdRepository.LOV_ParentQuery
                                Cache.CacheExt.AddInfiniteCacheObject(lookup.Value.ToString + "R", aMetaquery.ResultQuery)
                                Cache.CacheExt.AddInfiniteCacheObject(lookup.Value.ToString + "M", aMetaquery.MetaColumns)
                                Cache.CacheExt.AddInfiniteCacheObject(lookup.Value.ToString, aMetaquery)
                            Case Else
                                Cache.CacheExt.AddCacheObject(lookup.Value.ToString + "R", aMetaquery.ResultQuery)
                                Cache.CacheExt.AddCacheObject(lookup.Value.ToString + "M", aMetaquery.MetaColumns)
                                Cache.CacheExt.AddCacheObject(lookup.Value.ToString, aMetaquery)
                        End Select
                    Else
                        aMetaquery = DirectCast(objCache, MetaQuery)

                        objCache = Cache.CacheExt.GetCacheObject(lookup.Value.ToString + "R")
                        aMetaquery.ResultQuery = DirectCast(objCache, DataTable)
                        objCache = Cache.CacheExt.GetCacheObject(lookup.Value.ToString + "M")
                        aMetaquery.MetaColumns = DirectCast(objCache, DataTable)
                        objCache = Nothing
                    End If

                    If aMetaquery.CommandCategoryID = IdRepository.METALIST_METACOMMANDCATEGORIE_LKP Then
                        indexForLang = CommonExt.Base.AppManager.ApplicationOption.DescriptionColumnIndex - 1

                    Else
                        indexForLang = CommonExt.Base.AppManager.ApplicationOption.DescriptionColumnIndex
                    End If

                    aLOV = New RepositoryItemGridLookUpEdit() With {.DataSource = aMetaquery.ResultQuery, .DisplayMember = aMetaquery.ResultQuery.Columns(indexForLang).ToString, .ValueMember = aMetaquery.GUIDField, .PopupFormSize = New Size(800, 300), .NullText = "(none)"}


                    AddHandler aLOV.Popup, AddressOf OnActiveGridLookUpEditPopup

                    aLOV.Name = lookup.Value.ToString
                    aLOV.View.HorzScrollVisibility = Views.Base.ScrollVisibility.Always
                    aLOV.View.OptionsView.ColumnAutoWidth = False
                    aLOV.View.OptionsView.ShowAutoFilterRow = True
                    aLOV.View.OptionsBehavior.ReadOnly = True
                    'Afin que les GUID soit traduit dans un Excel...
                    aLOV.ExportMode = ExportMode.DisplayText

                    '
                    View = aLOV.View
                    View.Columns.Clear()
                    For Each row As DataRow In aMetaquery.MetaColumns.Rows
                        colname = row("ColumnName").ToString
                        hideCol = False
                        If AppManager.ApplicationOption.DescriptionColumnIndex = 2 Then
                            If colname.EndsWith("_ALT") Then
                                hideCol = True
                            End If
                        Else
                            If colname.EndsWith("_PRM") Then
                                hideCol = True
                            End If
                        End If
                        If hideCol = False Then
                            colVisible = CBool(IIf(CInt(row("pVisible")) = 0, False, True))
                            Column = View.Columns.AddField(colname)
                            Column.VisibleIndex = CInt(row("pOrder"))
                            Column.Caption = row("pCaption").ToString
                            Column.Visible = colVisible
                            Column.Width = CInt(row("pWidth"))
                            Column.ToolTip = row("pToolTip").ToString

                            formatType = DevExGridHelper.GetFormatType(row)
                            '
                            Column.DisplayFormat.FormatType = formatType
                            Column.DisplayFormat.FormatString = row("pNumberFormat").ToString
                        End If
                    Next
                    ' bug de memoire
                    'http://www.devexpress.com/Support/Center/p/B147229.aspx?searchtext=memory+leak&p=T4|P1|0
                    gridControl.RepositoryItems.Add(aLOV)
                    ' fin 
                    aView.Columns(lookup.Key).ColumnEdit = aLOV
                    'aView.Columns(lookup.Key).ColumnEditName = aMetaquery.QueryName
                    aMetaquery.Dispose()
                Else
                    aView.Columns(lookup.Key).ColumnEdit = aLOV
                End If
            Next
        Catch ex As Exception
            Throw
        End Try

    End Sub


    Public Shared Sub AssignLKP(ByVal aView As LayoutView, ByVal aMetaDataTable As MetaDataTable, ByVal gridControl As GridControl)
        Dim aMetaquery As MetaQuery
        Dim colVisible As Boolean
        Dim View As Views.Base.ColumnView '= aLOV.View
        Dim Column As DevExpress.XtraGrid.Columns.GridColumn
        Dim aLOV As RepositoryItemGridLookUpEdit
        Dim formatType As DevExpress.Utils.FormatType

        Dim indexForLang As Integer

        Dim hideCol As Boolean
        Dim colname As String

        Dim objCache As Object

        'TODO POUR TR: Tenir compte du TR si on la de défini dans la metaquery sinon utiliser le LOV

        For Each lookup As KeyValuePair(Of String, Guid) In aMetaDataTable.ListOfVisibleLookup
            aLOV = Nothing
            'Cherche si on a déjà ce LOV dans la grille
            For Each lov As RepositoryItem In gridControl.RepositoryItems
                If lov.Name = lookup.Value.ToString Then
                    aLOV = TryCast(lov, RepositoryItemGridLookUpEdit)
                End If
            Next

            'Si on l'a pas on le créer
            If aLOV Is Nothing Then
                'testPoint: Verify the GuidField in metaquery , The Guidfield is CASE sensitive, IE: ListvalueID is not equal to ListValueId
                'testPoint: LOV Query Must have the first 4 field Like GUID, Code, Desc_PRM, Desc_ALT in the SELECT Statement


                'TestPoint: On cache le résultat du LOV. (aMetaquery.ResultQuery)
                '           Les MetaColumns
                '           La metaquery
                objCache = Cache.CacheExt.GetCacheObject(lookup.Value.ToString)
                If objCache Is Nothing Then
                    aMetaquery = CommonExt.MetaQuery.GetMetaQueryById(lookup.Value)
                    aMetaquery.FillResultQuery()
                    Select Case aMetaquery.QueryID
                        'TestPoint: Core LOV are store in cache as long as possible
                        Case IdRepository.LOV_Lot, IdRepository.LOV_LotStatus, IdRepository.LOV_Product, IdRepository.LOV_SiteSection, IdRepository.LOV_TranType, IdRepository.LOV_Units, IdRepository.MetaLOVCaptions, IdRepository.MetaLOVToolTip, IdRepository.LOV_ParentQuery
                            Cache.CacheExt.AddInfiniteCacheObject(lookup.Value.ToString + "R", aMetaquery.ResultQuery)
                            Cache.CacheExt.AddInfiniteCacheObject(lookup.Value.ToString + "M", aMetaquery.MetaColumns)
                            Cache.CacheExt.AddInfiniteCacheObject(lookup.Value.ToString, aMetaquery)
                        Case Else
                            Cache.CacheExt.AddCacheObject(lookup.Value.ToString + "R", aMetaquery.ResultQuery)
                            Cache.CacheExt.AddCacheObject(lookup.Value.ToString + "M", aMetaquery.MetaColumns)
                            Cache.CacheExt.AddCacheObject(lookup.Value.ToString, aMetaquery)
                    End Select
                Else
                    aMetaquery = DirectCast(objCache, MetaQuery)

                    objCache = Cache.CacheExt.GetCacheObject(lookup.Value.ToString + "R")
                    aMetaquery.ResultQuery = DirectCast(objCache, DataTable)
                    objCache = Cache.CacheExt.GetCacheObject(lookup.Value.ToString + "M")
                    aMetaquery.MetaColumns = DirectCast(objCache, DataTable)
                    objCache = Nothing
                End If

                If aMetaquery.CommandCategoryID = IdRepository.METALIST_METACOMMANDCATEGORIE_LKP Then
                    indexForLang = CommonExt.Base.AppManager.ApplicationOption.DescriptionColumnIndex - 1

                Else
                    indexForLang = CommonExt.Base.AppManager.ApplicationOption.DescriptionColumnIndex
                End If

                aLOV = New RepositoryItemGridLookUpEdit() With {.DataSource = aMetaquery.ResultQuery, .DisplayMember = aMetaquery.ResultQuery.Columns(indexForLang).ToString, .ValueMember = aMetaquery.GUIDField, .PopupFormSize = New Size(800, 300), .NullText = "(none)"}

                AddHandler aLOV.Popup, AddressOf OnActiveGridLookUpEditPopup

                aLOV.Name = lookup.Value.ToString
                aLOV.View.HorzScrollVisibility = Views.Base.ScrollVisibility.Always
                aLOV.View.OptionsView.ColumnAutoWidth = False
                aLOV.View.OptionsView.ShowAutoFilterRow = True
                aLOV.View.OptionsBehavior.ReadOnly = True
                'Afin que les GUID soit traduit dans un Excel...
                aLOV.ExportMode = ExportMode.DisplayText
                '
                View = aLOV.View
                View.Columns.Clear()
                For Each row As DataRow In aMetaquery.MetaColumns.Rows
                    colname = row("ColumnName").ToString
                    hideCol = False
                    If AppManager.ApplicationOption.DescriptionColumnIndex = 2 Then
                        If colname.EndsWith("_ALT") Then
                            hideCol = True
                        End If
                    Else
                        If colname.EndsWith("_PRM") Then
                            hideCol = True
                        End If
                    End If
                    If hideCol = False Then
                        colVisible = CBool(IIf(CInt(row("pVisible")) = 0, False, True))
                        Column = View.Columns.AddField(colname)
                        Column.VisibleIndex = CInt(row("pOrder"))
                        Column.Caption = row("pCaption").ToString
                        Column.Visible = colVisible
                        Column.Width = CInt(row("pWidth"))
                        Column.ToolTip = row("pToolTip").ToString

                        formatType = DevExGridHelper.GetFormatType(row)
                        '
                        Column.DisplayFormat.FormatType = formatType
                        Column.DisplayFormat.FormatString = row("pNumberFormat").ToString
                    End If
                Next
                ' bug de memoire
                'http://www.devexpress.com/Support/Center/p/B147229.aspx?searchtext=memory+leak&p=T4|P1|0
                gridControl.RepositoryItems.Add(aLOV)
                ' fin 
                aView.Columns(lookup.Key).ColumnEdit = aLOV
                aView.Columns(lookup.Key).ColumnEditName = aMetaquery.QueryName
                aMetaquery.Dispose()
            Else
                aView.Columns(lookup.Key).ColumnEdit = aLOV
            End If
            'View.Dispose()
        Next
    End Sub


    Public Shared Function BuildLOV(ByVal aView As GridView, ByVal aMetaDataTable As MetaDataTable, ByVal gridControl As GridControl, ByVal colName As String) As RepositoryItemGridLookUpEdit
        Dim aMetaquery As MetaQuery
        Dim aLOV As RepositoryItemGridLookUpEdit = Nothing
        Dim mqGuid As Guid = Guid.Empty

        Dim View As Views.Base.ColumnView '= aLOV.View
        Dim Column As DevExpress.XtraGrid.Columns.GridColumn
        Dim hideCol As Boolean
        Dim colVisible As Boolean
        Dim formatType As DevExpress.Utils.FormatType

        Dim indexForLang As Integer


        If aMetaDataTable.ListOfVisibleLov.ContainsKey(colName) Then
            mqGuid = aMetaDataTable.ListOfVisibleLov(colName)
        End If

        If Not mqGuid = Guid.Empty Then
            aLOV = Nothing
            'Cherche si on a déjà ce LOV dans la grille
            For Each lov As RepositoryItem In gridControl.RepositoryItems
                If lov.Name = mqGuid.ToString Then
                    aLOV = TryCast(lov, RepositoryItemGridLookUpEdit)
                End If
            Next

            'Si on l'a pas on le créer
            If aLOV Is Nothing Then
                'testPoint: Verify the GuidField in metaquery , The Guidfield is CASE sensitive, IE: ListvalueID is not equal to ListValueId
                'testPoint: LOV Query Must have the first 4 field Like GUID, Code, Desc_PRM, Desc_ALT in the SELECT Statement
                aMetaquery = CommonExt.MetaQuery.GetMetaQueryById(mqGuid)
                aMetaquery.FillResultQuery()
                If aMetaquery.CommandCategoryID = IdRepository.METALIST_METACOMMANDCATEGORIE_LKP Then
                    indexForLang = CommonExt.Base.AppManager.ApplicationOption.DescriptionColumnIndex - 1

                Else
                    indexForLang = CommonExt.Base.AppManager.ApplicationOption.DescriptionColumnIndex

                End If
                aLOV = New RepositoryItemGridLookUpEdit() With {.DataSource = aMetaquery.ResultQuery, .DisplayMember = aMetaquery.ResultQuery.Columns(indexForLang).ToString, .ValueMember = aMetaquery.GUIDField, .PopupFormSize = New Size(800, 300), .NullText = "(none)"}

                AddHandler aLOV.Popup, AddressOf OnActiveGridLookUpEditPopup



                aLOV.Name = mqGuid.ToString
                aLOV.View.HorzScrollVisibility = Views.Base.ScrollVisibility.Always
                aLOV.View.OptionsView.ColumnAutoWidth = False
                aLOV.View.OptionsView.ShowAutoFilterRow = True
                aLOV.View.OptionsBehavior.ReadOnly = True
                'Afin que les GUID soit traduit dans un Excel...
                aLOV.ExportMode = ExportMode.DisplayText
                '
                View = aLOV.View
                View.Columns.Clear()
                For Each row As DataRow In aMetaquery.MetaColumns.Rows
                    colName = row("ColumnName").ToString
                    hideCol = False
                    If AppManager.ApplicationOption.DescriptionColumnIndex = 2 Then
                        If colName.EndsWith("_ALT") Then
                            hideCol = True
                        End If
                    Else
                        If colName.EndsWith("_PRM") Then
                            hideCol = True
                        End If
                    End If
                    If hideCol = False Then
                        colVisible = CBool(IIf(CInt(row("pVisible")) = 0, False, True))
                        Column = View.Columns.AddField(colName)
                        Column.VisibleIndex = CInt(row("pOrder"))
                        Column.Caption = row("pCaption").ToString
                        Column.Visible = colVisible
                        Column.Width = CInt(row("pWidth"))
                        Column.ToolTip = row("pToolTip").ToString

                        formatType = DevExGridHelper.GetFormatType(row)
                        '
                        Column.DisplayFormat.FormatType = formatType
                        Column.DisplayFormat.FormatString = row("pNumberFormat").ToString
                    End If
                Next
                ' bug de memoire
                'http://www.devexpress.com/Support/Center/p/B147229.aspx?searchtext=memory+leak&p=T4|P1|0
                gridControl.RepositoryItems.Add(aLOV)
                ' fin 
                aMetaquery.Dispose()
            End If
        End If
        Return aLOV
    End Function

    ''' <summary>
    ''' Assign color Property for Add and Serch Row in our Grid
    ''' </summary>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Public Shared Sub AssignSearchAndAddRowProperty(ByRef e As DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs)
        'On change la couleur des lignes de recherche et d'ajout
        If e.RowHandle = DevExpress.XtraGrid.GridControl.AutoFilterRowHandle Then
            e.Appearance.BackColor = Color.LightGoldenrodYellow
            e.Appearance.Font = New Font(e.Appearance.Font, FontStyle.Bold)
        End If
        If e.RowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle Then
            e.Appearance.BackColor = Color.LightGreen
            e.Appearance.ForeColor = Color.Black
        End If

    End Sub

    Private Shared Sub OnActiveGridLookUpEditPopup(sender As Object, e As EventArgs)
        Dim edit As GridLookUpEdit = CType(sender, GridLookUpEdit)
        edit.Properties.View.FocusedRowHandle = GridControl.AutoFilterRowHandle
        edit.Properties.View.FocusedColumn = edit.Properties.View.VisibleColumns(0)

    End Sub


End Class
